package routes

import (
	"net/http"
	"time"

	"gitee.com/zhenyangze/gin-framework/internal/app/bases"
	"gitee.com/zhenyangze/gin-framework/internal/app/providers"
	"gitee.com/zhenyangze/gin-framework/pkg/helpers"
	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

func Web(router *gin.Engine) {
	// Load templates
	if helpers.IsDir("resources/views/") {
		router.LoadHTMLGlob("resources/views/**/*")
	}

	// Basic routes
	router.GET("/", func(c *gin.Context) {
		c.String(200, "Gin Framework v2.0")
	})

	router.GET("/test", func(c *gin.Context) {
		c.JSON(200, bases.Json(0, "success", gin.H{
			"message": "测试接口正常",
			"time":    time.Now(),
		}))
	})

	// Helper function test
	router.GET("/md5/:str", func(c *gin.Context) {
		str := c.Param("str")
		c.JSON(http.StatusOK, bases.JsonOk("获取成功", helpers.Md5([]byte(str))))
	})

	// Redis test (if available)
	router.GET("/redis", func(c *gin.Context) {
		if providers.Redis == nil {
			c.JSON(500, bases.JsonError("Redis not available", nil))
			return
		}

		str2, _ := providers.Redis.Get("test_a").Result()
		if str2 == "" {
			str2 = helpers.RandString(32)
			providers.Redis.Set("test_a", str2, time.Second*10)
		}
		c.JSON(200, bases.JsonOk("Redis测试成功", str2))
	})

	// Database test (if available)
	router.GET("/db", func(c *gin.Context) {
		if providers.DB == nil {
			c.JSON(500, bases.JsonError("Database not available", nil))
			return
		}

		// Simple database ping test
		sqlDB, err := providers.DB.DB()
		if err != nil {
			c.JSON(500, bases.JsonError("Database connection error", err.Error()))
			return
		}

		if err := sqlDB.Ping(); err != nil {
			c.JSON(500, bases.JsonError("Database ping failed", err.Error()))
			return
		}

		c.JSON(200, bases.JsonOk("数据库连接正常", gin.H{
			"driver": "mysql",
			"status": "connected",
		}))
	})

	// Form validation test
	router.POST("/valid", func(c *gin.Context) {
		type UserInfo struct {
			Users    string `form:"user" binding:"required"`
			Password string `form:"password" binding:"required,min=6,max=12"`
		}

		var userinfo UserInfo
		err := c.ShouldBind(&userinfo)
		if err != nil {
			c.JSON(http.StatusBadRequest, bases.JsonError(err.Error(), nil))
			return
		}

		c.JSON(http.StatusOK, bases.JsonOk("验证通过", userinfo))
	})

	// Template test
	router.GET("/view", func(c *gin.Context) {
		c.HTML(200, "index.tmpl", gin.H{
			"time": time.Now(),
			"name": c.DefaultQuery("name", "Gin Framework"),
		})
	})

	// JSON performance test
	router.GET("/json", func(c *gin.Context) {
		data := gin.H{
			"framework": "gin",
			"version":   "2.0",
			"features": []string{
				"dependency injection",
				"structured logging",
				"health checks",
				"backward compatibility",
			},
			"timestamp": time.Now(),
		}
		c.JSON(200, bases.JsonOk("JSON测试", data))
	})
}
